<?php
namespace Custom\Controller;
use Think\Controller;
class AdminController extends UserController{

    public function index()
    {
        // var_dump($this->c_id);
        $this->list = M('account')->where("g.c_id = $this->c_id and g.is_son =1")->join('as g left join sp_role_son as k ON g.role_id = k.role_id')->field('g.*,k.role_name')->select();
        // var_dump($this->list);
        $this->display();
    }

    public function add()
    {
        if(IS_POST){
            $Admin = M('Account');
            if ( !I('post.') ){
                $this->error('添加失败');die;
            }
            $data['account_name'] = $account_name = I('username');
            $flag = $Admin->where("account_name = '$account_name'")->find();
            if ($flag) {
                die($this->error('账号已存在！'));
            }
            $data['c_id'] = $this->c_id;
            $data['role_id'] = I('role_id');
            if(I('post.s_id')){
                $data['s_id'] = I('post.s_id');
                $data['main'] = 1;
            }
            $data['password'] = md5(I('password'));
            // $data['password'] = md5(I('password'));
            $data['is_son'] = 1;
            $res = $Admin->add( $data );
            if ($res){
                $this->success('添加成功',U('index'),1);die;
            }else{
                $this->error('添加失败');die;
            }
        }
        //查询所有套餐
        $where['c_id'] = $this->c_id;
        $this->Rolelist = D('Role_son')->where($where)->select();
        $this->Storelist = M('store')->where($where)->select();
        $this->display();
    }
    /**
     * 删除后台管理员
     */
    public function del()
    {
        $id = I('get.id');
        $res = D('Account')->delete($id);
        $res?$this->success('删除成功',U('index'),1):$this->error('删除失败');
    }
    
    /**
     *编辑管理员权限
     */
    public function edit()
    {
        $id= I('get.id');
        $where['c_id'] = $this->c_id;
        $data = M('Account')->find($id);
        // var_dump($data);
        $this->assign('data',$data);
        $this->Rolelist = M('Role_son')->where($where)->select();
        if(IS_POST){
            $info['account_id']    =   I('post.account_id');
            $info['account_name'] = trim(I('post.username'));
            $info['role_id'] = I('post.role_id');
            if(I('post.s_id')){
                $info['s_id'] = I('post.s_id');
                $info['main'] = 1;
            }
            if(I('post.password')){
                $info['password'] = md5(I('password'));
            }
            $info['password'] = md5(I('post.password'));
            $res = M('Account')->save( $info );
            $res?$this->success('修改成功',U('index'),1):$this->error('修改失败');
        }else{
            $this->display();
        }

    }
}